<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Sysconfig extends ORM
{

    ///********************* PC端开始  ***********************///

    /**
     * @function 获取所有配置数组
     * @param int $webid
     * @return mixed
     */
    public static function config($webid = 0)
    {
        $sql = "select varname,value from sline_sysconfig where webid={$webid}";
        return DB::query(Database::SELECT, $sql)->execute()->as_array();
    }

    ///********************* PC端结束 ***************************///


    ///********************* 手机端开始  ***********************///

    /**
     * @function 获取所有配置数组
     * @param int $webid
     * @return mixed
     */
    public function get_config($webid)
    {
        $arr = $this->where('webid', '=', $webid)->get_all();
        $out = array();
        foreach ($arr as $row) {
            $out[$row['varname']] = $row['value'];
        }
        return $out;
    }
    ///********************* 手机端结束 ***************************///

    ///********************* 后台开始  ***********************///

    /**
     * @function 获取所有配置数组
     * @param $webid
     * @return array
     */
    public function getConfig($webid)
    {
        $arr = $this->where('webid', '=', $webid)->get_all();
        $out = array();
        foreach ($arr as $row) {
            $out[$row['varname']] = $row['value'];
        }
        return $out;
    }

    /**
     * @function 保存配置信息
     * @param $arr
     * @return bool
     * @throws Kohana_Exception
     */
    public function saveConfig($arr)
    {
        $webid = ARR::get($arr, 'webid');

        foreach ($arr as $k => $v) {
            /* if(!get_magic_quotes_gpc())
             {
                 $v = addslashes($v);
             }
             else
             {
                 $v = $v;
             }*/
            if ($k !== 'webid') {
                $row = $this->where('webid', '=', $webid)->and_where('varname', '=', $k)->find();
                if ($k == 'cfg_logourl'&& $v && !preg_match('~https?://~', $v)) {
                    $v = (Request::initial()->secure() ? 'https://' . $v : 'http://').$v;
                }
                if (isset($row->id)) //如果存在则修改,如果不存在则创建
                {

                    //$v = $k=='cfg_tongjicode' ? addslashes($v) : $v;
                    $row->value = $v;
                    $row->update();
                }
                else {
                    $row->varname = $k;
                    $row->value = $v;
                    $row->webid = $webid;
                    $row->create();
                }

                $row->clear();
            }

        }
        //  $this->writeConfig($webid);
        self::write_config($webid);
        return true;
    }

    /**
     * @function 写配置缓存文件
     * @param $webid
     */
    public function writeConfig($webid)
    {

        $configfile = $this->getConfigFilePath($webid);
        $fp = fopen($configfile, 'wb');
        flock($fp, 3);
        fwrite($fp, "<" . "?php\r\n");
        $arr = ORM::factory('sysconfig')->where('webid', '=', $webid)->get_all();
        // if($webid==0)//主站配置信息
        // {
        foreach ($arr as $row) {

            if ($row['varname'] == 'cfg_tongjicode') {
                fwrite($fp, "\${$row['varname']} = '" . addslashes($row['value']) . "';\r\n");
            }
            else {
                fwrite($fp, "\${$row['varname']} = '" . str_replace("'", '', $row['value']) . "';\r\n");
            }

        }
        fwrite($fp, "?" . ">");
        fclose($fp);

    }


    /**
     * @function 获取配置文件信息
     * @param $webid
     * @return string
     */
    private function getConfigFilePath($webid)
    {
        if ($webid == 0) {
            $file = SLINEDATA . '/config.cache.inc.php';
        }
        else {
            $path = SLINEDATA . '/config';
            if (!is_dir($path)) mkdir($path, 0777, true);
            $webinfo = Common::getWebInfo($webid);
            $file = SLINEDATA . '/config/config.' . $webinfo['webprefix'] . '.php';
        }
        return $file;
    }

    /**
     * @function 获取系统版本
     * @param null $platfrom
     * @return array
     */
    public static function system_version($platfrom = NULL)
    {
        $version = array();
        $rs = DB::select('value', 'varname')->from('sysconfig')->where('varname', 'in', array('cfg_pc_version', 'cfg_mobile_version'))->execute()->as_array();
        foreach ($rs as $v) {
            $version[$v['varname']] = $v['value'];
        }
        if ($platfrom) {
            return $version[$platfrom];
        }
        return $version;
    }

    /**
     * @function 获取系统配置
     * @param int $webid
     * @param null $fields 要获取的字段数组或字符
     * @param $isvalue 是否直接返回值
     * @return array
     */
    public static function get_configs($webid = 0, $fields = null, $isvalue = null)
    {

        $query = DB::select('value', 'varname')->from('sysconfig')->where('webid', '=', $webid);
        if (is_array($fields))
            $query->and_where('varname', 'in', $fields);
        if (is_string($fields))
            $query->and_where('varname', '=', $fields);
        $list = $query->execute()->as_array();
        $out = array();
        foreach ($list as $row) {
            if ($isvalue)
                return $row['value'];
            $out[$row['varname']] = $row['value'];
        }

        return $out;
    }

    ///********************* 后台结束  ***********************///

    /**
     * @function 获取系统配置
     * @param $field
     * @param $varname
     * @param int $webid
     * @return mixed
     */
    public static function get_sys_conf($field, $varname, $webid = 0)
    {
        $result = DB::select($field)->from('sysconfig')->where('varname', '=', $varname)->and_where('webid', '=', $webid)->execute()->current();
        return $result[$field];
    }

    /**
     * @function 保存配置
     * @param array $arr (包括至少一个键webid和cfg开头的配置项)
     * @return bool
     * @throws Kohana_Exception
     */
    public static function save_config($arr)
    {
        $webid = $arr['webid'];
        foreach ($arr as $k => $v) {
            if ($k !== 'webid') {
                $row = ORM::factory('sysconfig')->where('webid', '=', $webid)->and_where('varname', '=', $k)->find();

                if (isset($row->id)) //如果存在则修改,如果不存在则创建
                {

                    //$v = $k=='cfg_tongjicode' ? addslashes($v) : $v;
                    $row->value = $v;
                    $row->update();
                }
                else {
                    $row->varname = $k;
                    $row->value = $v;
                    $row->webid = $webid;
                    $row->create();
                }
                $row->clear();
            }

        }
        self::write_config($webid);
        return true;
    }

    //支付

    /**
     * 根据站点获取配置
     * @param int $webid
     * @return array
     */
    public static function payment_config($webid = 0)
    {
        $sql = "select varname,value from sline_sysconfig where webid={$webid}";
        $arr = DB::query(Database::SELECT, $sql)->execute()->as_array();
        $out = array();
        foreach ($arr as $row) {
            $out[$row['varname']] = $row['value'];
        }
        return $out;
    }

    public static function write_config($webid)
    {

        $sys_prefix = '';
        if ($webid == 0) {
            $sys_prefix = St_Functions::get_main_prefix();
        }
        else {
            $sub_prefix = DB::select('webprefix')->from('weblist')->where('id', '=', $webid)->execute()->get('webprefix');
            $sys_prefix = empty($sub_prefix) ? $sys_prefix : $sub_prefix;
        }
        $file = CACHE_DIR . 'v5/config.' . $sys_prefix . '.php';


        //缓存文件不存在
        // if (!file_exists($file))
        //{
        $data = self::config($webid);
        $config = array();
        foreach ($data as $v) {
            $config[$v['varname']] = trim($v['value']);
        }
        if (!isset($config['cfg_m_img_url'])) {
            $config['cfg_m_img_url'] = $config['cfg_m_main_url'];
        }
        if ($webid > 0) {
            $main = self::config(0);
            //子站只有一个页面效果
            $config['cfg_index_templet'] = '';
            foreach ($main as $v) {
                if (!isset($config[$v['varname']])) {
                    $config[$v['varname']] = trim($v['value']);
                }
            }
        }
        file_put_contents($file, '<?php defined(\'SYSPATH\') or die(\'No direct script access.\');' . PHP_EOL . 'return ' . var_export($config, true) . ';');
        // }
        $data = require_once($file);
        return $data;
    }

    /**
     * @function 获取可报价的人群，
     * @param $choosed_people_str 已经存在的人群的编号的数组，比如 array(1,3,6)
     * @param $is_all 是否获取所有可用分组，包括没有选中的。
     */
    public static function get_people_group($choosed_people_arr=null,$is_all=null)
    {
        $field = array('cfg_line_adult_name','cfg_line_child_name','cfg_line_old_name',
            'cfg_line_people4_name','cfg_line_people5_name','cfg_line_people6_name','cfg_line_people_open');
        $config = self::get_configs(0, $field);
        $people_open_arr = explode(',',$config['cfg_line_people_open']);
        $people_open_arr = empty($people_open_arr)? array(2,1,3):$people_open_arr;
        $people_open_arr = !empty($choosed_people_arr) && is_array($choosed_people_arr)? array_unique(array_merge($people_open_arr,$choosed_people_arr)):$people_open_arr;
        $adult = !empty($config['cfg_line_adult_name']) ? $config['cfg_line_adult_name'] : '成人';
        $child = !empty($config['cfg_line_child_name']) ? $config['cfg_line_child_name'] : '儿童';
        $old   = !empty($config['cfg_line_old_name']) ? $config['cfg_line_old_name'] : '老人';
        $people_info_arr = array(
            '2'=>array('name'=>$adult,'basicprice_field'=>'adultbasicprice','profit_field'=>'adultprofit','price_field'=>'adultprice','identifier'=>'2'),
            '1'=>array('name'=>$child,'basicprice_field'=>'childbasicprice','profit_field'=>'childprofit','price_field'=>'childprice','identifier'=>'1'),
            '3'=>array('name'=>$old,'basicprice_field'=>'oldbasicprice','profit_field'=>'oldprofit','price_field'=>'oldprice','identifier'=>'3'),
            '4'=>array('name'=>$config['cfg_line_people4_name'],'basicprice_field'=>'people4_basicprice','profit_field'=>'people4_profit','price_field'=>'people4_price','identifier'=>'4'),
            '5'=>array('name'=>$config['cfg_line_people5_name'],'basicprice_field'=>'people5_basicprice','profit_field'=>'people5_profit','price_field'=>'people5_price','identifier'=>'5'),
            '6'=>array('name'=>$config['cfg_line_people6_name'],'basicprice_field'=>'people6_basicprice','profit_field'=>'people6_profit','price_field'=>'people6_price','identifier'=>'6')
        );
        foreach($people_info_arr as $k=>$row)
        {
            if(empty($row['name']))
            {
                unset($people_info_arr[$k]);
            }
        }
        if($is_all)
        {
            return $people_info_arr;
        }

        $people_arr = array();
        foreach($people_info_arr as $people_info)
        {
            if(in_array($people_info['identifier'],$people_open_arr))
            {
                $people_arr[$people_info['identifier']]= $people_info;
            }
        }
        return $people_arr;
    }

    /**
     * 获取一条配置数据
     * @param $varname
     * @return mixed|null
     */
    public static function get_one_config($varname)
    {
        return DB::select()
            ->from('sysconfig')
            ->where('varname', '=', $varname)
            ->execute()
            ->current();
    }
}